package com.xuecheng.gateway.filters;

import com.alibaba.fastjson.JSON;
import com.xuecheng.commons.model.vo.AuthInfo;
import com.xuecheng.commons.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;

import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URLEncoder;
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @SneakyThrows
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.获取请求路径
        String path = request.getURI().getPath();
        //2.放行不需要鉴定token的请求
        if (path.contains("coursePub/preview") ||
                path.contains("login") ||
                path.contains("basic/dictionary") ||
                path.contains("category/tree-nodes") ||
                path.contains("course/upload") ||
                path.contains("search/")) {
            return chain.filter(exchange);
        }
        //3.获取token，使用JWTs工具类校验token是否合法
        String token = request.getHeaders().getFirst("Authorization");
        Boolean verifyToken = JwtUtils.verifyToken(token);
        //不合法，就响应状态码401
        if (!verifyToken) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //4.解析token，获取map数据
        Claims claims = JwtUtils.parserToken(token).getBody();
        Long userId = claims.get("userId", Long.class);
        Long companyId = claims.get("companyId", Long.class);
        String companyName = claims.get("companyName", String.class);
        //5.将以上数据封装到对象中
        AuthInfo info = new AuthInfo();
        info.setUid(userId);
        info.setCompanyId(companyId);
        info.setCompanyName(companyName);
        //6、设置一个新的请求头参数（解析后的明文数据）
        String json = URLEncoder.encode(JSON.toJSONString(info),"UTF-8");
        //创建一个httpRequest的请求对象
        ServerHttpRequest httpRequest = request.mutate().headers(httpHeaders -> {
            httpHeaders.set("payload", json);
        }).build();
        //将此请求对象，写入到微服务转发的上下文中
        exchange.mutate().request(httpRequest);
        return chain.filter(exchange);
    }
    //指定多个过滤器时此过滤器的执行顺序
    @Override
    public int getOrder() {
        return 0;
    }
}
